package com.xin.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.xin.dao.PermissionDao;
import com.xin.dao.RoleDao;
import com.xin.dao.UserDao;
import com.xin.pojo.Permission;
import com.xin.pojo.Role;
import com.xin.pojo.User;
import com.xin.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Set;

/**
 * @Author 夜天
 * @Date 2021/12/21 10:15
 * @Version 1.0.0
 * @description：
 */
@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private PermissionDao permissionDao;
    // 根据用户名查询用户信息和角色信息
    @Override
    public User findByUsername(String username) {
        User user = userDao.findByUsername(username);
        if(username == null){
            return null;
        }
        Integer userId = user.getId();
        Set<Role> roles = roleDao.findByUserId(String.valueOf(userId));
        for (Role role : roles) {
            Integer roleId = role.getId();
            // 根据角色 id 查询相关的权限
            Set<Permission> permissions = permissionDao.findByRoleId(roleId);
            // 让角色关联权限
            role.setPermissions(permissions);
        }
        // 让用户关联角色
        user.setRoles(roles);
        return user;
    }
}
